<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
<!--    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">-->
    <th:block th:include="include :: header('智能问答')"/>
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/css/iconfont/iconfont.css}" rel="stylesheet">
    <link th:href="@{/ajax/libs/bootstrap-tagsinput/tagsinput.css}" rel="stylesheet">
    <link th:href="@{/ajax/libs/jQuery-ui/jquery-ui.css}" rel="stylesheet">
    <link th:href="@{/css/style.css}">
</head>
<style>
    * {
        padding: 0;
        margin: 0;
    }

    .chat_left_item {
        width: 50px;
        height: 50px;
        background-color: #4459AB;
        float: left;
        margin-right: 10px;
        text-align: center;
        line-height: 50px;
        color: white;
        border-radius: 25px;
    }

    .chat_right_item {
        width: 50px;
        height: 50px;
        background-color: #4459AB;
        float: right;
        margin-top: 10px;
        text-align: center;
        line-height: 50px;
        color: white;
        border-radius: 25px;
    }

    /* foot */
    .chat_foot {
        height: 100px;
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
        position: relative;
    }

    .chat_context {
        width: 100%;
        height: 100%;
        font-size: 17px;
        box-sizing: border-box;
        outline: none;
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
        border-width: 0px;
        padding: 16px;
    }

    .chat_commit {
        width: 80px;
        color: white;
        background-color: #4F7cff;
        line-height: 30px;
        text-align: center;
        border-radius: 5px;
        position: absolute;
        right: 10px;
        bottom: 20px;
        margin-right: 10px;
        cursor: pointer;
    }

    .chat_context {
        resize: none;
    }

    .chat_context::placeholder {
        color: black;
        font-weight: 500;
    }

    .line {
        width: 100%;
        margin-top: 20px;
        border-top: 1px;
        border-color: rgb(62, 148, 195);
        border-style: solid;
    }

    .message {
        position: relative;
        display: flex;
        width: 100%;
        margin: 5px 0;
        border: 0;
    }

    .message p {
        position: relative;
        right: 0;
        /*text-align: right;*/
        max-width: 65%;
        padding: 10px;
        background: #3e94c3;
        border-radius: 10px;
        font-size: 0.9em;
    }

    .message p span {
        display: block;
        margin-top: 5px;
        font-size: 0.6em;
        opacity: 0.5;
    }

    .my_message {
        color: white;
        text-align: left;
        justify-content: flex-end;
    }

    .fre_message {
        justify-content: flex-start;
    }

    .fre_message p {
        background: rgba(240, 233, 233, 0.98);
        text-align: left;
    }

</style>
<body style="letter-spacing:2px;font-family:'huawen' ;font-weight: bold">
<!-- entry -->
<div>
    <div class="col-sm-12">
        <input name="userName" id="userName" th:value="${user.userName}" type="hidden">
        <input name="userNo" id="userNo" th:value="${user.userNo}" type="hidden">
        <!-- middle -->
        <div class="col-sm-12" id="chat_box" style="overflow-y: scroll;height: 420px;"></div>
        <!-- button -->
        <div class="col-sm-12" style="height: 30px;">
            <div class="col-sm-4" style="margin-top: 10px;float: right;">
                <button type="button" class="btn btn-sm btn-warning" id="anew_answer" onclick="anewAnswer()">重新解答&nbsp;<i
                        class="fa fa-spin fa-refresh" aria-hidden="true"></i></button>&nbsp;&nbsp;&nbsp;
                <button type="button" class="btn btn-sm btn-primary" id="big_model_answer" onclick="bigModelAnswer()">
                    大模型解答&nbsp;<i
                        class="fa fa-spin fa-connectdevelop" aria-hidden="true"></i></button>
            </div>

            <span id="loading_wait" style="color: chocolate;display: none"><i class="fa fa-spin fa-spinner"
                                                                              aria-hidden="true"></i>正在努力思考中，请耐心等待哦！</span>
        </div>
        <!-- 分割线 -->
        <div class="line col-sm-12"></div>
        <!-- foot -->
        <div class="col-sm-12 chat_foot">
            <!-- context -->
            <textarea class="chat_context" id="questions" cols="30" rows="10"
                      placeholder="请输入问题 点击发送键发送"></textarea>
            <button class="btn btn-sm btn-warning chat_commit" id="send" onclick="sendQuestions()">发送</button>
        </div>
    </div>
</div>
</body>
<th:block th:include="include :: footer"/>
<script th:src="@{/js/jquery.min.js}"></script>
<script th:src="@{/js/bootstrap.min.js}"></script>
<script th:src="@{/ajax/libs/bootstrap-tagsinput/tagsinput.min.js}"></script>
<script th:src="@{/ajax/libs/jQuery-ui/jquery-ui.js}"></script>
<script th:src="@{/ajax/libs/qxEasyUI/jquery.easyui.min.js}"></script>
<script th:src="@{/common/js/hm-ui.js}"></script>

<script>
    var prefix = ctx + "system/bdapi/intelligent";
    var send_message = document.getElementById("chat_box");
    var questions = document.getElementById("questions");
    var anew = [];
    var types = [];
    var link_url = '';
    var isOpen = [[${isOpen}]];
    var timesAll = [[${timesAll}]];
    var timesDay = [[${timesDay}]];
    var numsBig = [[${numsBig}]];

    $(function () {
        $("#anew_answer").attr('disabled', true).addClass('forbidden');
        if (isOpen > 0) {
            $("#send").attr('disabled', true).addClass('forbidden');
        } else {
            if (timesDay <= 0) {
                if (timesAll <= 0) {
                    $("#send").attr('disabled', true).addClass('forbidden');
                } else {
                    $("#send").attr('disabled', false).removeClass('forbidden');
                }
            } else {
                $("#send").attr('disabled', false).removeClass('forbidden');
            }
            $("#send").attr('disabled', false).removeClass('forbidden');
        }

        if (numsBig <= 0) {
            $("#big_model_answer").attr('disabled', true).addClass('forbidden');
        } else {
            $("#big_model_answer").attr('disabled', false).removeClass('forbidden');
        }
        if (anew.length > 0) {
            $("#anew_answer").attr('disabled', false).removeClass('forbidden');
        }
    });

    //提问
    function sendQuestions() {
        let content = questions.value;
        if (content.length <= 0) {
            return $.modal.msgError("请输入问题！");
        } else {
            sendContent(content);
        }
    }

    //发送问题
    function sendContent(content) {
        question_html(content);
        //更新重新解答
        anew = [content];
        types = ["ai"];
        let user_no = $("#userNo").val();
        let config = {
            url: prefix + '/questions',
            type: "post",
            dataType: "json",
            data: {
                "question": content,
                "pageSizeDi": 5,
                "pageSizeGuo": 5,
                "userid": user_no,
                "pCode": "510000",
                "adCode": "510100",
                "askId": "0",
                "xqid": "",
                "zdName": ""
            },
            beforeSend: function () {
                let await = '<i class="fa fa-spin fa-spinner" aria-hidden="true"></i>正在努力思考中，请耐心等待哦！';
                loadingAwaitOpen(await);
            },
            success: function (result) {
                if (result.code === 0) {
                    loadingAwaitClose();
                    let data = result.data;
                    let sensitiveWord = data.msg.text; //触发敏感词
                    if (sensitiveWord) {
                        answer_html(sensitiveWord, '');
                        return false;
                    }
                    let sceneQA = data.msg.QAScene;// 闲聊
                    if (sceneQA) {
                        answer_html(sceneQA, '');
                        return false;
                    }
                    let noAnswer = data.msg.noresult0; //无结果
                    if (noAnswer) {
                        answer_html(noAnswer, '');
                        return false;
                    }
                    let bot = data.msg.bot;
                    let friendlyRes = data.msg.friendly; //友好回答
                    let mattersList = data.msg.Matters; //反问结果集
                    let resList;
                    if (data.msg.list) {
                        resList = data.msg.list.全部;
                    }
                    //多个回答结果集
                    if (bot) {
                        let answerContents = bot.answerContents;
                        let text = answerContents[0].text;
                        let ansList = answerContents[0].list;
                        let addButton = "";
                        if (ansList) {
                            for (let i = 0; i < ansList.length; i++) {
                                addButton += add_button(ansList[i]);
                            }
                        }
                        answer_html(text, addButton);
                        return false;
                    } else if (mattersList) {
                        if (mattersList.length > 0) {
                            answer_html(mattersList[0], '');
                            return false;
                        }
                    } else if (resList) {
                        let addLink = "";
                        if (friendlyRes) {
                            for (let i = 0; i < resList.length; i++) {
                                let val = resList[i]
                                addLink += add_link(val.lmname, val.sjfl, val.xqurl, val.subtitle, val.loadtime, val.zdname)
                            }
                            answer_html(friendlyRes, addLink);
                        }
                    }
                }
            }
        };
        $.ajax(config);
    }

    //重新解答
    function anewAnswer() {
        if (anew.length <= 0) {
            return false;
        }
        if (types.length <= 0) {
            return false;
        } else if (types[0] === 'ai') {
            sendContent(anew[0]);
        } else if (types[0] === 'big_model') {
            bigSendContent(anew[0]);
        }
    }

    //大模型解答
    function bigModelAnswer() {
        let content = questions.value;
        if (content.length <= 0) {
            return $.modal.msgError("请输入问题！");
        } else {
            bigSendContent(content);
        }
    }

    function bigSendContent(content) {
        question_html(content);
        //更新重新解答
        anew = [content];
        types = ["big_model"];
        let config = {
            url: prefix + "/questionAnswering",
            type: "post",
            dataType: "json",
            data: {
                "content": content,
            },
            beforeSend: function () {
                let await = '<i class="fa fa-spin fa-spinner" aria-hidden="true"></i>大模型全力解答中 请耐心等待哦！'
                loadingAwaitOpen(await);
            },
            success: function (result) {
                loadingAwaitClose();
                if (result.result) {
                    answer_html(result.result, '');
                }
                if (result.code === 500){
                    $.modal.msgError(result.msg)
                    $("#big_model_answer").attr('disabled', true).addClass('forbidden');
                }
            },
            error: function (res) {
                loadingAwaitClose();
                return $.modal.msgError(res.msg)
            }
        };
        $.ajax(config);
    }

    //自动定位到最下方
    function autoPosition() {
        send_message.scrollTop = send_message.scrollHeight;
    }

    //问题
    function question_html(content) {
        let user_name = $("#userName").val();
        let time = getNowDateStr();
        let sub_script = user_name === "" ? time : user_name + "（" + time + "）";
        let ans_html = '<div class="col-sm-12 message"><div class="message my_message">' +
            '<p>' + content + '<br><span>' + sub_script + '</span></p>' +
            '</div><div class="chat_right_item"><i class="fa fa-user-circle" aria-hidden="true"></i></div></div>';
        let add_Html = document.createElement("div");
        add_Html.innerHTML = ans_html;
        send_message.append(add_Html);
        questions.value = "";
        autoPosition();
    }

    //当前时间 按格式
    function getNowDateStr() {
        let date = new Date();
        let hour = date.getHours();
        let min = date.getMinutes();
        min = min > 9 ? min : "0" + min;
        return hour + ':' + min;
    }

    //答案
    function answer_html(content, other_html) {
        content = formatterContent(content);
        if (content === '') return;
        let time = getNowDateStr();
        let sub_script = "AI" + "（" + time + "）";
        let qus_html = '<div class="message fre_message">' +
            '<div class="chat_left_item"><i class="fa fa-android" aria-hidden="true"></i></div>' +
            '<p>' + content + '<br/><span>' + sub_script + '</span></p>' +
            '</div><div style="margin: -15px 0 0 70px;">' + other_html + '</div>';
        let add_Html = document.createElement("div");
        add_Html.innerHTML = qus_html;
        send_message.append(add_Html);
        autoPosition();
    }

    //添加按钮
    function add_button(content) {
        return '<button type="button" class="btn btn-sm btn-warning" style="margin:10px;" onclick="ans_button(this)">' + content + '</button>';
    }

    //添加链接
    function add_link(lm_name, data_type, detail_url, subtitle, load_time, from_name) {
        link_url = detail_url;
        return '<div class="col-sm-12 work-box" style="display:block;"><div class="work-box-top"><div class="col-sm-12 work-box-top-box">' +
            '<div class="col-sm-10"><span>栏目：' + lm_name + '(' + data_type + ')' + '</span></div>' +
            '</div><div class="col-sm-12 work-box-class">' +
            '<a style="color: inherit" href="' + link_url + '" target="_blank" title="点击跳转到网页详情">' + subtitle + '</a></div>' +
            '<div class="col-sm-12 work-box-buttom">' +
            '<div class="col-sm-6">' + load_time + '</div>' +
            '<div class="col-sm-4">' +
            '<div class="col-sm-12 entering-pd">来自：' + from_name + '</div>' +
            '</div></div></div></div>'
    }

    //按钮
    function ans_button(res) {
        let content = $(res).html()
        sendContent(content)
    }

    //格式化内容
    function formatterContent(content) {
        if (content === undefined) {
            return '';
        }
        if (content.indexOf('<a/>') !== -1) {
            content = content.replace('<a/>', '</a>');//a标签替换
        }
        return content;
    }

    // 加载动画
    function loadingAwaitOpen(val) {
        let loading = document.getElementById("loading_wait");
        if (loading.style.display === "none") {
            loading.style.display = "inline-block"
            if (val !== "" && val !== undefined) {
                loading.innerHTML = val;
            }
            $("#send").attr('disabled', true).addClass('forbidden');
            $("#anew_answer").attr('disabled', true).addClass('forbidden');
            $("#big_model_answer").attr('disabled', true).addClass('forbidden');
        }
    }

    // 关闭加载动画
    function loadingAwaitClose() {
        document.getElementById("loading_wait").style.display = "none"
        $("#send").attr('disabled', false).removeClass('forbidden');
        $("#anew_answer").attr('disabled', false).removeClass('forbidden');
        $("#big_model_answer").attr('disabled', false).removeClass('forbidden');
    }
</script>
</html>